const Router = require('koa-router');
const tasks = require('../models/tasks');
const { authenticate } = require('../middleware/auth');
const router = new Router();
router.prefix('/api/tasks');

// 新建任务 (需要登录)
router.post('/', authenticate, async (ctx) => {
  const { text } = ctx.request.body;
  const userId = ctx.state.user.id; // 从 token 中获取用户 ID
  const result = tasks.addTask(text, userId);
  ctx.body = result;
});

// 更新任务 (需要登录)
router.put('/:id', authenticate, async (ctx) => {
  const { id } = ctx.params;
  const { text } = ctx.request.body;
  const result = tasks.updateById(text, id);
  ctx.body = result;
});

// 删除任务 (需要登录)
router.delete('/:id', authenticate, async (ctx) => {
  const { id } = ctx.params;
  const result = tasks.removeById(id);
  ctx.body = result;
});

// 获取任务列表 (需要登录)
router.get('/', authenticate, async (ctx) => {
  const userId = ctx.state.user.id; // 从 token 中获取用户 ID
  const rows = tasks.getAllByUserId(userId); // 根据用户 ID 获取任务
  ctx.body = rows;
});


module.exports = router;



